import { handleActions as createReducer } from 'redux-actions'
import { addProductToLocalCart, changeLocalProductNumber, deleteProductFromLocalCart, saveCarts } from '../actions/cart.action'

const initialState = []

const handleAddProductToLocalCart = (state, action) => {
    // 1. 要添加的商品不在购物车中
    // 2. 要添加的商品已经添加在购物车

    // 将原有的购物车数据拷贝
    const newState = JSON.parse(JSON.stringify(state))
    const product = newState.find(product => product.id === action.payload.id)
    if (product) {
        // 商品已经存在于购物车中
        product.count = product.count + 1
    } else {
        // 商品不在购物车中
        newState.push(action.payload)
    }
    return newState
}

// 将服务端返回的商品列表数据同步到本地的购物车中
const handleSaveCarts = (state, action) => action.payload

// 删除本地购物车中的商品
const handleDeleteProductFromLocalCart = (state, action) => {
    // 将原有的购物车数据拷贝
    const newState = JSON.parse(JSON.stringify(state))
    const index = newState.findIndex(product => product.id === action.payload)
    newState.splice(index, 1)
    return newState
}

const handleChangeLocalProductNumber = (state, action) => {
    // 将原有的购物车数据拷贝
    const newState = JSON.parse(JSON.stringify(state))
    const product = newState.find(product => product.id === action.payload.id)
    product.count = action.payload.count
    return newState
}

export default createReducer({
    [addProductToLocalCart]: handleAddProductToLocalCart,
    [saveCarts]: handleSaveCarts,
    [deleteProductFromLocalCart]: handleDeleteProductFromLocalCart,
    [changeLocalProductNumber]: handleChangeLocalProductNumber
}, initialState)